﻿Imports System
Imports System.Diagnostics
Imports System.Web
Imports System.Workflow.Runtime

Namespace System.Workflow.Runtime.Hosting
    Public NotInheritable Class WorkflowWebHostingModule
        Implements IHttpModule
        ' Methods
        Public Sub New()
            WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "Workflow Web Hosting Module Created")
        End Sub

        Private Sub OnAcquireRequestState(ByVal sender As Object, ByVal e As EventArgs)
            WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "WebHost Module Routing Begin")
            Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies.Get("WF_WorkflowInstanceId")
            If (Not cookie Is Nothing) Then
                HttpContext.Current.Items.Add("__WorkflowInstanceId__", New Guid(cookie.Value))
            End If
        End Sub

        Private Sub OnReleaseRequestState(ByVal sender As Object, ByVal e As EventArgs)
            If (HttpContext.Current.Request.Cookies.Get("WF_WorkflowInstanceId") Is Nothing) Then
                Dim cookie As New HttpCookie("WF_WorkflowInstanceId")
                Dim obj2 As Object = HttpContext.Current.Items.Item("__WorkflowInstanceId__")
                If (Not obj2 Is Nothing) Then
                    cookie.Value = obj2.ToString
                    HttpContext.Current.Response.Cookies.Add(cookie)
                End If
            End If
        End Sub

        Private Sub System.Web.IHttpModule.Dispose() Implements IHttpModule.Dispose
        End Sub

        Private Sub System.Web.IHttpModule.Init(ByVal application As HttpApplication) Implements IHttpModule.Init
            WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "Workflow Web Hosting Module Initialized")
            Me.currentApplication = application
            AddHandler application.ReleaseRequestState, New EventHandler(AddressOf Me.OnReleaseRequestState)
            AddHandler application.AcquireRequestState, New EventHandler(AddressOf Me.OnAcquireRequestState)
        End Sub


        ' Fields
        Private currentApplication As HttpApplication
    End Class
End Namespace

